package com.lv.suyiyong.hfr.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.util.isNotEmpty
import androidx.core.util.size
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.SizeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.material.imageview.ShapeableImageView
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.adapter.SubAdapter
import com.lv.common.base.BaseActivity
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.isJson
import com.lv.common.ktx.isTextOverflowing
import com.lv.common.ktx.setSafeListener
import com.lv.common.ktx.zero
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.TimeUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.linkbar.ZFlowLayout
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.common.widget.video.YGXVideoTopPlayer
import com.lv.service.adapter.RecyclerTextAdapter
import com.lv.service.bean.AddressDetailsBean
import com.lv.service.bean.CertificationBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.bean.LEDBeans
import com.lv.service.bean.ViewTypeBean
import com.lv.service.bean.ViewTypeStringBean
import com.lv.service.dialog.ListSingleTextTagPopupView
import com.lv.service.dialog.ShowCenterTextPopupView
import com.lv.service.dialog.ShowCodeBorderPopupView
import com.lv.service.event.TabPageEvent
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.CollectOrAttentionBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.UserUtils
import com.lv.service.utils.YgxAroutPageKt
import com.lv.service.weidget.picker.ListSingleTextPopupView
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BannerMediaNoBroderAdapter
import com.lv.suyiyong.hfr.adapter.CompanyGoodsHorAdapter
import com.lv.suyiyong.hfr.adapter.CompanyHomeAddressAdapter
import com.lv.suyiyong.hfr.adapter.CompanyLedAdapter
import com.lv.suyiyong.hfr.adapter.CompanyRecomeGoodsAdapter
import com.lv.suyiyong.hfr.adapter.MediaTypeNoPlayAdapter
import com.lv.suyiyong.hfr.databinding.FragmentCompanyFactoryBinding
import com.lv.suyiyong.hfr.databinding.FragmentCompanyHomeBinding
import com.lv.suyiyong.hfr.ui.CompanyInfoActivity
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.enums.PopupPosition
import com.youth.banner.Banner
import com.youth.banner.listener.OnPageChangeListener
import com.youth.banner.transformer.ZoomOutPageTransformer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/10 3:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述： NewTemplate 1 公司首页 黑色模板
 */
class CompanyFactoryFragment : BaseFragment(), OnClickListener {
    private var mCompanyInfo: CompanyItemBean? = null
    private var mBannerAdapter: BannerMediaNoBroderAdapter? = null
    private var mBannerBeans = mutableListOf<ViewTypeBean>()
    private val mAddressBeans = mutableListOf<CommonSelectedBean>()
    private var mBannerPicBeans = mutableListOf<ViewTypeBean>()
    private var mFactoryAdapter: MediaTypeNoPlayAdapter? = null
    private var mCertificationAdapter: BaseQuickAdapter<CertificationBean, BaseViewHolder>? = null
    private var mCertificationDatas = mutableListOf<CertificationBean>()
    private var mCertifiDatas = mutableListOf<ViewTypeStringBean>()
    private var inTentPosition = 0//跳转时轮播的位置
    private var inTentAction = false//跳转时轮播的位置
    private var mShowCompanyDecPop = false
    private var mAddressAdapter: CompanyHomeAddressAdapter? = null
    private var mSiteBeans = mutableListOf<AddressDetailsBean>()

    private var mCompanyCpName = ""
    private var mTxaccid = ""
    private var mLogin = false
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentCompanyFactoryBinding? = null

    override fun getLayoutRes() = R.layout.fragment_company_factory

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentCompanyFactoryBinding.bind(view).apply {
            initSingleClickListener(tvDes, ivCode, tvInfoMore)
        }
        return mBinding!!
    }


    override fun initConfig() {
        super.initConfig()
        mAddressBeans.clear()
        mAddressBeans.add(
            CommonSelectedBean(
                "腾讯地图",
                postiont = R.drawable.icon_map_tunxun
            )
        )
        mAddressBeans.add(
            CommonSelectedBean(
                "高德地图",
                postiont = R.drawable.icon_map_gaode
            )
        )
        mAddressBeans.add(
            CommonSelectedBean(
                "百度地图",
                postiont = R.drawable.icon_map_baidu
            )
        )

    }

    private fun initBanner() {


        mBannerAdapter = BannerMediaNoBroderAdapter(mBannerBeans)
        mBinding?.banner?.adapter = mBannerAdapter
        mBinding?.banner?.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                if (mBannerBeans[position].type == ViewTypeBean.VEDIO_TYPE) {
                    startVideo(position)
                } else {
                    stopVideo()
                }
                inTentPosition = position

            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
//                ?.setOnBannerListener(OnBannerListener<ViewTypeBean> { data, position ->
//                    val json = GsonUtils.toJson(mBannerBeans)
//                    ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
//                        .withInt("position", position)
//                        .withString("data", json)
//                        .navigation()
//                })
        mBannerAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            inTentAction = true
            YgxAroutPageKt.scanMediaType(mBannerBeans, position - 1)
        }
    }

    private var mVideo: YGXVideoTopPlayer? = null
    private fun startVideo(position: Int) {
        val vhMap = mBannerAdapter?.getVHMap()
        if (vhMap != null && vhMap.isNotEmpty() && vhMap.size > 0) {
            val viewHolder = vhMap.valueAt(0)
            if (viewHolder is BannerMediaNoBroderAdapter.BannerNoBorderMyViewVideoHolder) {
                mVideo = viewHolder.mVideo
                mVideo?.startPlayLogic()
            }
        }
    }

    private fun stopVideo() {
        if (mVideo == null) {
            if (mBannerBeans.size > 0 && mBannerBeans[0].type == ViewTypeBean.VEDIO_TYPE) {
                val get = mBannerAdapter?.getVHMap()?.valueAt(0)
                val viewHolder =
                    get as BannerMediaNoBroderAdapter.BannerNoBorderMyViewVideoHolder
                mVideo = viewHolder.mVideo
            }
        }
        mVideo?.onVideoPause()
    }


    private fun initAdapter() {
        //禁止滑动  布局管理器
        val linearFactoryLayoutManager: LinearLayoutManager =
            object : LinearLayoutManager(requireContext()) {
                //禁止竖向滑动 RecyclerView 为垂直状态（VERTICAL）
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
        mBinding?.rvFactory?.layoutManager = linearFactoryLayoutManager
        mFactoryAdapter = MediaTypeNoPlayAdapter(mBannerPicBeans)
        mBinding?.rvFactory?.adapter = mFactoryAdapter
        mBinding?.rvFactory?.addItemDecoration(
            SpacesItemDecoration(SizeUtils.dp2px(10.0f), SizeUtils.dp2px(10.0f), false)
        )
        mFactoryAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            inTentAction = true
            YgxAroutPageKt.scanMediaType(mBannerPicBeans, position)

        }

        mAddressAdapter = CompanyHomeAddressAdapter(mSiteBeans)
        mBinding?.rvAddress?.adapter = mAddressAdapter
        mAddressAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            showMapSelected(data)
        }

        mCertificationAdapter = object :
            BaseQuickAdapter<CertificationBean, BaseViewHolder>(
                R.layout.item_certification, mCertificationDatas
            ) {
            override fun convert(holder: BaseViewHolder, item: CertificationBean) {
                val imageView = holder.getView<ImageView>(R.id.iv_image)
                val tvName = holder.getView<TextView>(R.id.tv_name)
                imageView.LoadSrc(item.image)
                tvName.text = item.name
                val layoutPosition = holder.layoutPosition
                val clParent = holder.getView<ConstraintLayout>(R.id.cl_parent)
                val layoutParams = clParent.layoutParams as RecyclerView.LayoutParams
                if (layoutPosition == 0) {
                    layoutParams.leftMargin = SizeUtils.dp2px(10.0f)
                } else {
                    layoutParams.leftMargin = SizeUtils.dp2px(3.0f)
                }
                clParent.layoutParams = layoutParams
                clParent.setSafeListener {
                    YgxAroutPageKt.scanMediaPicType(mCertifiDatas, layoutPosition)
                }
            }
        }

        mBinding?.rvCertification?.adapter = mCertificationAdapter

    }

    override fun initData() {
        super.initData()
        arguments?.let {
            mCompanyInfo = it.getParcelable<CompanyItemBean>("companyBean")
        }
        mTxaccid = mCompanyInfo?.txaccid ?: ""
        mCompanyCpName = mCompanyInfo?.name ?: ""
        initAdapter()
        val displayFac = mCompanyInfo?.displayFac
        displayFac?.let {
            var picCount = 0
            var videoCount = 0
            displayFac.indices.forEach { i ->
                val type = displayFac[i].type
                var mType = ViewTypeBean.PIC_TYPE
                if (type == "1") {
                    mType = ViewTypeBean.VEDIO_TYPE
                    videoCount++
                } else {
                    picCount++
                }
                mBannerBeans.add(ViewTypeBean(mType, displayFac[i]))
                mBannerPicBeans.add(ViewTypeBean(mType, displayFac[i]))
            }
            if (videoCount > 0) {
                mBinding?.banner?.isAutoLoop(false)
            } else {
                mBinding?.banner?.isAutoLoop(true)
                mBinding?.banner?.setLoopTime(1500)
            }
        }
        mBinding?.tvVist?.text = "${mCompanyInfo?.access ?: 0}"
        mBinding?.tvFans?.text = "${mCompanyInfo?.attentionnum ?: 0}"
        mBinding?.tvCir?.text = "${mCompanyInfo?.totalnum ?: 0}"
        mBinding?.tvCommit?.text = "${mCompanyInfo?.communicationnum ?: 0}"
        val bnames = mCompanyInfo?.merito ?: ""
        val isJson = bnames.isJson()
        var bname = ""
        if (isJson) {
            val jsonType = object : TypeToken<List<String>>() {}.type
            val bnams: List<String> = GsonUtils.fromJson(bnames, jsonType)
            bnams.forEach { bname = "$bname、$it" }
        } else {
            bname = bnames.replace(",", "、")
        }
        if (bname.startsWith("、")) {
            bname = bname.drop(1)
        }
        mBinding?.tvBname?.text = "主营商品：$bname"
        when (mCompanyInfo?.isspecially) {
            "2" -> {
                mBinding?.cvCompanyInfo?.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_fff0d2_fffbf0_5)
                mBinding?.clAddress?.setBackgroundResource(com.lv.common.R.drawable.bg_half_b_fffdf9_5)
            }
        }
        initAddress()
        val acreage = mCompanyInfo?.acreage ?: 0
        val scale = mCompanyInfo?.scale ?: 0
        if (acreage > 0) {
            mBinding?.tvAcreage?.visibility = View.VISIBLE
            mBinding?.tvAcreage?.text = "工厂面积：${acreage}㎡"
        }
        if (scale > 0) {
            mBinding?.tvScale?.visibility = View.VISIBLE
            mBinding?.tvScale?.text = "工厂规模：${scale}人"
        }
        mBinding?.tvIdentification?.text = "统一社会信用代码：${mCompanyInfo?.identification}"
        mBinding?.tvTime?.text =
            TimeUtil.getDateTimeString(mCompanyInfo?.created ?: 0, "yyyy年MM月dd日")
        val catption = mCompanyInfo?.caption ?: "这个用户很懒，什么都没有留下~"
        mBinding?.tvDes?.text = catption
        mBinding?.tvDes?.post {
            val (textOverflowing, num) = mBinding?.tvDes!!.isTextOverflowing(3)
            if (textOverflowing) {
                mShowCompanyDecPop = true
                mBinding?.ivDesArrow?.visibility = View.VISIBLE
                val substring = catption.substring(0, num - 5)
                mBinding?.tvDes?.text = "${substring}…"
            } else {
                mShowCompanyDecPop = false
                mBinding?.ivDesArrow?.visibility = View.GONE
            }
//            LogUtils.e(textOverflowing.toString())
        }
        mFactoryAdapter?.notifyDataSetChanged()
        initBanner()

        initCertification()
    }

    private fun initAddress() {
        mSiteBeans.clear()
        var mAddress = mCompanyInfo?.prefecture ?: ""
        if (mAddress.isNotEmpty()) {
            mAddress =
                "${mCompanyInfo?.province}${mCompanyInfo?.city}${mCompanyInfo?.area}${mCompanyInfo?.prefecture}${mCompanyInfo?.address}"
        } else {
            mAddress = "${mCompanyInfo?.address}"
        }
        mSiteBeans.add(AddressDetailsBean(mAddress, "", "", "", "", "3"))

        mAddressAdapter?.notifyDataSetChanged()

    }


    private fun initCertification() {
        val mWatermarking = mCompanyInfo?.watermarking ?: ""
        val certification = mCompanyInfo?.certification
        certification?.let {
            mCertificationDatas.clear()
            mCertifiDatas.clear()
            certification.forEach { item ->
                item.image = item.image + mWatermarking
                mCertifiDatas.add(ViewTypeStringBean(item.image, 0))
            }
            mCertificationDatas.addAll(certification)
            mCertificationAdapter?.notifyDataSetChanged()
            mBinding?.rvCertification?.visibility =
                if (certification.isEmpty()) View.GONE else View.VISIBLE
        }


    }

    private fun showMapSelected(address: String) {
        val mPopupView =
            ListSingleTextTagPopupView(
                requireContext(), mAddressBeans,
            ) { current, data ->
                if (current != -1) {
//                    mAddress="湖北省武汉市长江大桥"
                    when (current) {
                        0 -> {
                            val installed = MyUtils.isInstalled("com.tencent.map")
                            if (installed) {
                                val i1 = Intent()
                                //调起腾讯地图APP，在上海搜索美食
                                i1.data =
                                    Uri.parse("qqmap://map/search?keyword=$address&referer=速易甬")
                                startActivity(i1)
                            } else {
                                showToast("请安装腾讯地图")
                            }
                        }

                        1 -> {
                            val installed = MyUtils.isInstalled("com.autonavi.minimap")
                            if (installed) {
                                val intent = Intent()
                                intent.action = Intent.ACTION_VIEW
                                intent.addCategory(Intent.CATEGORY_DEFAULT)
                                //将功能Scheme以URI的方式传入data
                                val uri =
                                    Uri.parse("androidamap://poi?sourceApplication=速易甬&keywords=$address")
                                intent.data = uri
                                //启动该页面即可
                                startActivity(intent)
                            } else {
                                showToast("请安装高德地图")
                            }
                        }

                        2 -> {
                            val installed = MyUtils.isInstalled("com.baidu.BaiduMap")
                            if (installed) {
                                val i1 = Intent()
                                // 驾车导航
                                i1.data = Uri.parse("baidumap://map/navi?query=$address")
                                startActivity(i1)
                            } else {
                                showToast("请安装百度地图")
                            }
                        }
                    }
                }
            }


        XPopup.Builder(requireContext())
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_des -> {
                if (mShowCompanyDecPop) {
                    showInterDuceDialog()
                }
            }

            R.id.iv_code -> showCodeDialog()

            R.id.tv_info_more -> {
                if (mLogin) {
                    UserUtils.showChatActivity(mTxaccid, mCompanyCpName)
                } else {
                    ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
                }
            }
        }
    }

    //二维码展示
    private fun showCodeDialog() {
        val url = ""
//            "${Constants.KEY_SHARE_HEADER_SYY}${Constants.KEY_SHARE_COMPANY}${mCompanyInfo?.id}${Constants.KEY_SHARE_COMPANY_PRO}$mForshort"
        val popupView =
            ShowCodeBorderPopupView(
                requireContext(), url, mCompanyInfo?.image ?: ""
            )
        XPopup.Builder(requireContext())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .asCustom(popupView)
            .show()
    }

    private fun showInterDuceDialog() {
        val popupView =
            ShowCenterTextPopupView(requireContext(), "企业简介", mCompanyInfo?.caption ?: "")
        XPopup.Builder(requireContext())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .asCustom(popupView)
            .show()
    }

    override fun onResume() {
        super.onResume()
        LogUtils.e("aaaaaaaaaaaaaaaaaa--onResume")
        if (inTentAction) {
            if (mBannerBeans.isNotEmpty() && mBannerAdapter != null && mBannerBeans[inTentPosition].type == ViewTypeBean.VEDIO_TYPE) {
                startVideo(inTentPosition)
            }
            inTentAction = false
        }
    }

    override fun onPause() {
        super.onPause()
        mVideo?.onVideoPause()
        inTentAction = true
    }

    override fun onDestroy() {
        super.onDestroy()
        mVideo?.release()
    }


    companion object {
        fun newInstance(companyBean: CompanyItemBean?): CompanyFactoryFragment {
            val args = Bundle()
            args.putParcelable("companyBean", companyBean)

            val fragment = CompanyFactoryFragment()
            fragment.arguments = args
            return fragment
        }
    }


}